Page({
  data: {
    points: [],
    timer: null,
    time: 0,
    initWave: [69,64,54,42,28,14,-4,-22,-44,-68,-92,-18,-14,-18,-19,-21,-22,-28,-20,-26,-27,-26,-26,-25,-24,-22,-20,-19,-17,-15,-13,-12,-14,-90,-78,-66,-56,-48,-38,-30,-24,-16,-8,0,8,18,28,38,48,58,68]
  },

  onLoad() {
    this.initCanvas();
  },

  onUnload() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  initCanvas() {
    const query = wx.createSelectorQuery();
    query.select('#heartRateCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        
        // 设置canvas大小
        const dpr = wx.getSystemInfoSync().pixelRatio;
        canvas.width = res[0].width * dpr;
        canvas.height = res[0].height * dpr;
        ctx.scale(dpr, dpr);

        // 初始化点数组
        const points = [];
        for (let i = 0; i < res[0].width; i++) {
          points.push({
            x: i,
            y: res[0].height / 2
          });
        }
        this.setData({ points });

        // 开始动画
        this.startAnimation(ctx, canvas.width / dpr, canvas.height / dpr);
      });
  },

  // 生成波形
  generateWave(time) {
    // 主波形
    const mainWave = Math.sin(time * 0.06) * 30;
    
    // 添加次波形，使曲线更自然
    const subWave1 = Math.sin(time * 0.12) * 8;
    const subWave2 = Math.sin(time * 0.03) * 5;
    
    // 组合所有波形
    return mainWave + subWave1 + subWave2;
  },

  startAnimation(ctx, width, height) {
    const draw = () => {
      // 清除画布
      ctx.clearRect(0, 0, width, height);
      
      // 更新点的位置
      const points = this.data.points;
      points.pop(); // 移除最后一个点
      
      // 生成新的点
      const time = this.data.time;
      const newY = height / 2 + this.generateWave(time);
      points.unshift({ // 在数组开头添加新点
        x: 0,
        y: newY
      });

      // 更新所有点的x坐标
      points.forEach(point => {
        point.x += 2; // 向右移动
      });

      // 绘制波形
      ctx.beginPath();
      ctx.strokeStyle = '#00ff00';
      ctx.lineWidth = 2;
      
      // 计算断点位置（使用时间来控制断点移动）
      const breakPoint = Math.floor(points.length * (this.data.time % 100) / 100);
      const breakWidth = 20; // 断点宽度
      
      // 绘制第一段（断点前）
      for (let i = 0; i < breakPoint; i++) {
        if (i === 0) {
          ctx.moveTo(points[i].x, points[i].y);
        } else {
          ctx.lineTo(points[i].x, points[i].y);
        }
      }
      ctx.stroke();
      
      // 绘制第二段（断点后）
      ctx.beginPath();
      for (let i = breakPoint + breakWidth; i < points.length; i++) {
        if (i === breakPoint + breakWidth) {
          ctx.moveTo(points[i].x, points[i].y);
        } else {
          ctx.lineTo(points[i].x, points[i].y);
        }
      }
      ctx.stroke();

      // 更新时间
      this.setData({ 
        points,
        time: time + 1
      });
    };

    const timer = setInterval(draw, 32);
    this.setData({ timer });
  }
});
